import 'package:get/get.dart';
import '../models/chat_model.dart';

class ChatListController extends GetxController {
  // 聊天列表数据，使用RxList使其成为可观察的
  final RxList<ChatModel> chatList = <ChatModel>[].obs;

  @override
  void onInit() {
    super.onInit();
    // 加载模拟数据
    loadMockData();
  }

  // 加载模拟数据
  void loadMockData() {
    chatList.addAll([
      ChatModel(
        id: '1',
        name: '妈妈',
        lastMessage: '嗯',
        time: '2025/03/08',
        avatar: 'assets/images/avatar1.png',
        hasUnread: false,
      ),
      ChatModel(
        id: '2',
        name: '逍遥自在2群',
        lastMessage: '[10条] 一个书生: 喵喵喵还是个外卖',
        time: '21:13',
        avatar: 'assets/images/group1.png',
        hasUnread: true,
        unreadCount: 10,
      ),
      ChatModel(
        id: '3',
        name: '太理校集A10',
        lastMessage: '👉: 出车锁和女士篮球mp://tbvj390PdxDZ9Be...',
        time: '21:08',
        avatar: 'assets/images/group2.png',
        hasUnread: true,
      ),
      ChatModel(
        id: '4',
        name: '鲜气食足★T3 (海西金谷) 订餐...',
        lastMessage: '[3条] 鲜气食足: [图片]',
        time: '21:06',
        avatar: 'assets/images/group3.png',
        hasUnread: true,
      ),
      ChatModel(
        id: '5',
        name: '邹昊邑',
        lastMessage: '南京江宁出发的',
        time: '21:05',
        avatar: 'assets/images/avatar2.png',
        hasUnread: false,
      ),
      ChatModel(
        id: '6',
        name: '公众号',
        lastMessage: 'Gitee: [链接] 登录通知',
        time: '21:01',
        avatar: 'assets/images/official.png',
        hasUnread: true,
      ),
      ChatModel(
        id: '7',
        name: '悦购超市玖珑汇顾客2群',
        lastMessage: '[5条] 悦购超市玖珑汇店17768294108: 2025年...',
        time: '21:01',
        avatar: 'assets/images/group4.png',
        hasUnread: true,
      ),
      ChatModel(
        id: '8',
        name: '【财务】前后端打包群(23)',
        lastMessage: '刷新几次 有时可以有时不行',
        time: '21:00',
        avatar: 'assets/images/group5.png',
        hasUnread: true,
        unreadCount: 23,
      ),
    ]);
  }

  // 跳转到聊天详情页
  void toChat(String id) {
    final chat = chatList.firstWhere((chat) => chat.id == id);

    // 跳转到聊天详情页
    Get.toNamed(
      '/chat-detail',
      arguments: {
        'chatId': id,
        'title': chat.name,
      },
    );

    // 标记为已读
    final index = chatList.indexWhere((chat) => chat.id == id);
    if (index != -1) {
      final updatedChat = ChatModel(
        id: chat.id,
        name: chat.name,
        lastMessage: chat.lastMessage,
        time: chat.time,
        avatar: chat.avatar,
        hasUnread: false,
        unreadCount: null,
      );
      chatList[index] = updatedChat;
    }
  }

  // 跳转到新建聊天页
  void toNewChat() {
    Get.toNamed('/new-chat');
  }

  // 跳转到搜索页面
  void toSearch() {
    Get.toNamed('/search');
  }

  // 搜索聊天
  void searchChat(String keyword) {
    // 实现搜索逻辑
  }
}
